# Post editing bot
# by Cee Pee

import forumapi

def settings(settings):
	settings.add_option("-p", "--posts", type="int", help="post IDs to work on", metavar="IDS")
	settings.add_option("--thread", type="int", help="thread ID to work on")
	settings.add_option("-x", "--text", help="text to post")
	settings.add_option("-t", "--title", help="new title")
	settings.add_option("-s", "--search", help="string to search posts with" metavar="TEXT")
	settings.add_option("-r", "--replace", help="text to replace --search with in found posts")
	settings.add_option("-f", "--forums", type="int", help="forum IDs to restrict to")
	settings.add_option("--reason", help="reason for editing")
	settings.add_option("--append", type="bool", default=True, reverse={"opt_str": "--overwrite", "help": "overwrite the post"}, help="append the text")
	settings.add_option("--loop", type="bool", default=True, help="keep editing after the first post")

def main(me, settings, args):
	forums = []
	if options.forums:
		for forum in options.forums:
			try:
				forums.append(forumapi.Forum(me, id=int(forum)))
			except:
				pass
	
	thread = None
	if options.thread:
		thread = forumapi.Thread(me, id=int(options.thread))
	
	if options.posts:
		posts = []
		for post in options.posts:
			try:
				posts.append(forumapi.Post(me, id=int(post)))
			except:
				pass
	elif options.search:
		posts = me.get_search_results(options.search, forums=forums)
	elif thread:
		posts = thread.posts
	else:
		raise(forumapi.OptionError("Post IDs or text to search required."))
	
	if not(options.text or options.replace):
		raise(forumapi.OptionError("Text required."))
	
	for post in posts:
		if (forums and post.thread.forum not in forums) or (thread and post.thread != thread):
			continue
		
		if options.text:
			post.edit(options.text, title=options.title, reason=options.reason, append=options.append)
		else:
			prepared_post = post.prepare_edit()
			
			if options.title:
				prepared_post.title = options.title
			
			prepared_post.message = prepared_post.message.replace(options.search, options.replace)
			
			prepared_post.post_data["reason"] = options.reason
			
			prepared_post.submit()
		
		if not options.loop:
			break
	
	print("Done.")

if __name__ == "__main__":
	forumapi.run(main, options=settings, supported_types=["vbulletin", "vanilla"])
